package city.spring.modules.oldman.service.impl;

import city.spring.modules.bed.service.BedManagementService;
import city.spring.modules.bed.vo.BedInfoVO;
import city.spring.modules.oldman.entity.OldmanBedEntity;
import city.spring.modules.oldman.repository.OldmanBedRepository;
import city.spring.modules.oldman.service.OldmanBedService;
import city.spring.modules.oldman.vo.OldmanBedVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Service：老人入住床位
 *
 * @author 谢金婷
 * @date 2020-08-18 17:22:40
 */
@CacheConfig(cacheNames = {OldmanBedServiceImpl.CACHE_NAME})
@Transactional(rollbackFor = Exception.class)
@Service
public class OldmanBedServiceImpl extends ServiceImpl<OldmanBedRepository, OldmanBedEntity> implements OldmanBedService {

    private final OldmanBedRepository oldmanBedRepository;
    private final BedManagementService bedManagementService;

    public OldmanBedServiceImpl(OldmanBedRepository oldmanBedRepository, BedManagementService bedManagementService) {
        this.oldmanBedRepository = oldmanBedRepository;
        this.bedManagementService = bedManagementService;
    }

    @Override
    public void saveOldmanBed(OldmanBedEntity entity) {
        if (!save(entity)) {
            throw new RuntimeException("保存信息失败");
        }
    }

    @Override
    public void updateOldmanBed(OldmanBedEntity entity) {
        // 使用 updateById(entity); 修改数据时，将会修改 entity 对象中所有非null数据，如果某个字段为null，将会忽略该字段的修改
        if (!updateById(entity)) {
            throw new RuntimeException("修改信息失败");
        }
    }

    @Override
    public void deleteOldmanBed(String primaryKey) {
        removeById(primaryKey);
    }

    @Override
    public void deleteOldmanBed(List<String> primaryKeys) {
        removeByIds(primaryKeys);
    }

    @Override
    public OldmanBedEntity getBedInfoByoldmanId(String oldmanId) {
        OldmanBedEntity oldmanBedEntity = oldmanBedRepository.getBedInfoByoldmanId(oldmanId);
        if (oldmanBedEntity instanceof OldmanBedVO) {
            BedInfoVO bedInfo = bedManagementService.getBedInfo(oldmanBedEntity.getBedId());
            OldmanBedVO vo = (OldmanBedVO) oldmanBedEntity;
            vo.setBuilding(bedInfo.getBuilding());
            vo.setFloor(bedInfo.getFloor());
            vo.setRoom(bedInfo.getRoom());
            vo.setBed(bedInfo.getBed());
        }
        return oldmanBedEntity;
    }

    @Override
    public List<OldmanBedVO> getBedByPersonId(String personId) {
        return oldmanBedRepository.getBedByPersonId(personId);
    }

    @Override
    public OldmanBedVO getBedPriceAndDiscountByPersonId(String personId) {
        return oldmanBedRepository.getBedPriceAndDiscountByPersonId(personId);
    }
}